package com.byx.chatserver.service.impl;

import com.byx.chatserver.mapper.INumberPoolMapper;
import com.byx.chatserver.service.INumberPoolService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * NumberPoolServiceImpl
 *
 * @author Superb
 * @date 2021/2/12 16:33
 */
@Service
public class NumberPoolServiceImpl implements INumberPoolService {
    private final Logger logger = LoggerFactory.getLogger(NumberPoolServiceImpl.class);
    private INumberPoolMapper numberPoolMapper;

    private static final int MIN_AVAIL_NUMBER_SIZE = 10;
    private static final int CREATE_NUMBER_LIST_SIZE = 10;

    @Autowired
    public void setNumberPoolMapper(INumberPoolMapper numberPoolMapper) {
        this.numberPoolMapper = numberPoolMapper;
    }

    @Override
    public synchronized String selectNumber() {
        Long number = numberPoolMapper.getNextNumber();
        numberPoolMapper.updateStatus(number);
        return String.valueOf(number);
    }

    @Async
    @Override
    public synchronized void execute() {
        logger.info("当前线程：" + Thread.currentThread());
        int poolSize = numberPoolMapper.queryAvailableNumberPoolSize();
        logger.info("数据库号码池中目前存在" + poolSize);
        if (poolSize <= MIN_AVAIL_NUMBER_SIZE){
            long lastNumber = numberPoolMapper.getLastNumber();
            logger.info("最大号码是:" + lastNumber + ",再插入" + CREATE_NUMBER_LIST_SIZE + "个号码");
            Long[] numbers = new Long[MIN_AVAIL_NUMBER_SIZE];
            for (int i = 0;i<MIN_AVAIL_NUMBER_SIZE;i++){
                numbers[i] = lastNumber + 1 + i;
            }
            logger.info("生成了" + CREATE_NUMBER_LIST_SIZE + "个号码：" + Arrays.toString(numbers) + ",插入数据库号码池");
            numberPoolMapper.insertNumber(numbers);
            logger.info("插入号码池成功！");
        }
    }
}
